<template>
  <div class="">
    <!-- head -->
    <el-affix :offset="94">
      <div class="card affix-container pt15 pb14">
        <el-page-header @back="router.go(-1)">
          <template #content>
            <span class="fsize16">{{ isEdit ? "编辑入库单据" : "新增入库单据" }}</span>
          </template>
          <template #extra>
            <div class="foot">
              <el-button @click="router.go(-1)">取消</el-button>
              <el-button @click="onSubmit" type="primary">保存</el-button>
              <!-- <el-button @click="onCheck" type="primary">{{ isEdit ? "编辑" : "新增" }}并审核</el-button> -->
            </div>
          </template>
        </el-page-header>
      </div>
    </el-affix>
    <!-- head end -->
    <div class="card mt10">
      <el-form :model="purchaseForm" label-width="120px" :rules="couponRules" ref="ruleFormRef" :inline="true">
        <!-- 订单信息 -->
        <div class="group">
          <div class="section-title">订单信息</div>
          <el-form-item label="供应商" prop="supplierId">
            <el-select class="width320" v-model="purchaseForm.supplierId">
              <el-option v-for="unit in supplierList" :label="unit.name" :value="unit.id" :key="unit.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="单据编号" prop="orderNo">
            <el-input class="width320" v-model="purchaseForm.orderNo" />
          </el-form-item>
          <el-form-item label="入库日期" prop="date">
            <el-date-picker class="width320" v-model="purchaseForm.date" type="date" value-format="YYYY-MM-DD" />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input class="width500" v-model="purchaseForm.remark" placeholder="请填写" :rows="4" type="textarea" />
          </el-form-item>
        </div>
        <div class="group">
          <div class="section-title">商品信息</div>
          <el-form-item label="" prop="stockindetailList">
            <el-button class="mb10" type="primary" @click="openSelectTreeTable('商品选择')">添加商品</el-button>
            <el-table :data="purchaseForm.stockindetailList" size="small">
              <el-table-column type="index" label="序号" width="60" />
              <el-table-column prop="goodsName" label="商品名称" />
              <el-table-column prop="productName" label="商品规格" />
              <el-table-column prop="quantity" label="入库数量" align="center">
                <template #default="scope">
                  <el-input-number
                    class="w100"
                    v-model="scope.row.quantity"
                    :controls="false"
                    :min="1"
                    :disabled="scope.row.isGift"
                    @change="onChangeAmo(scope.$index)"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="price" label="入库单价" align="center">
                <template #default="scope">
                  <el-input-number
                    class="w100"
                    :controls="false"
                    v-model="scope.row.price"
                    :disabled="scope.row.isGift"
                    @change="onChangeAmo(scope.$index)"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="amount" label="金额" align="center" />
              <el-table-column prop="taxRate" label="税率" align="center">
                <template #default="scope">
                  <el-input-number class="w100" :controls="false" v-model="scope.row.taxRate" />
                </template>
              </el-table-column>
              <el-table-column prop="isGift" label="是否赠品" align="center">
                <template #default="scope">
                  <el-switch v-model="scope.row.isGift" />
                </template>
              </el-table-column>
              <el-table-column prop="giftQuantity" label="赠送数量" align="center">
                <template #default="scope">
                  <el-input-number
                    class="w100"
                    :controls="false"
                    v-model="scope.row.giftQuantity"
                    :disabled="!scope.row.isGift"
                  />
                </template>
              </el-table-column>
              <!-- <el-table-column prop="onLine" label="是否上架">
              <template #default="scope">
                <el-switch v-model="scope.row.onLine" size="small" />
              </template>
            </el-table-column> -->
              <el-table-column prop="operate" label="操作" align="center">
                <template #default="scope">
                  <el-button type="danger" size="small" @click="delSpecRow(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <SelectTreeTable @selected-list="handleSelectedTreeList" ref="selectTreeTableRef" />
  </div>
</template>
<script setup lang="ts" name="waresEdit">
import { ref, reactive, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import SelectTreeTable from "@/components/SelectTreeData/index.vue";
import {
  createStockin,
  editStockin,
  getStockin,
  getSupplierList,
  getWaresCategoryList,
  getWaresList
} from "@/api/modules/inventory";
import type { FormInstance } from "element-plus";
import { replaceArrayItems } from "@/utils";
// import { getStoreList } from "@/api/modules/operation";

const router = useRouter();
const route = useRoute();
const ruleFormRef = ref<FormInstance>();
const isEdit = ref(false);
const purchaseForm = reactive({
  id: 0,
  orderType: 1,
  orderNo: "",
  supplierId: "",
  date: "",
  status: 1,
  checkFlag: 1,
  remark: "",
  sourceId: "",
  printStatus: 0,
  stockindetailList: []
});
const couponRules = reactive({
  orderNo: [{ required: true, message: "请填写订单编号" }],
  stockindetailList: [{ required: true, message: "请添加商品" }]
});

const delSpecRow = (index: number) => {
  purchaseForm.stockindetailList.splice(index, 1);
};

const handleSelectedTreeList = (val: any) => {
  if (val.list.length > 0) {
    let list = val.list.map(im => {
      return {
        goodsName: im.name,
        goodsId: im.id,
        products: im.productName,
        productsId: im.prodcutId,
        productName: im.productName,
        quantity: 1,
        price: im.posPrice,
        amount: im.posPrice,
        taxRate: 0,
        isGift: false,
        giftQuantity: 0
      };
    });
    purchaseForm.stockindetailList = replaceArrayItems(list, purchaseForm.stockindetailList, "goodsId");
    // purchaseForm.stockindetailList = list;
  }
};

const onSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      if (isEdit.value) {
        await editStockin(purchaseForm).then(() => {
          router.push({
            path: "/inventory/warehousing",
            query: {
              upList: true
            }
          });
        });
      } else {
        await createStockin(purchaseForm).then(() => {
          router.push({
            path: "/inventory/warehousing",
            query: {
              upList: true
            }
          });
        });
      }
    } catch (error) {
      console.log(error);
    }
  });
};
const onChangeAmo = (index: number) => {
  purchaseForm.stockindetailList[index].amount = (
    purchaseForm.stockindetailList[index].price * purchaseForm.stockindetailList[index].quantity
  ).toFixed(2);
};
const selectTreeTableRef = ref<InstanceType<typeof SelectTreeTable> | null>(null);
const openSelectTreeTable = (title: string) => {
  const params = {
    title,
    isView: false,
    index: 0,
    selTags: purchaseForm.stockindetailList.map(i => {
      i.name = i.name;
      i.id = i.goodsId;
      return i;
    }),
    columns: [
      { type: "selection", width: 80 },
      { prop: "name", label: "商品名称", align: "left" },
      { prop: "posPrice", label: "商品价格" }
    ],
    idName: "goodsCategoryId",
    treeApi: getWaresCategoryList,
    api: getWaresList
  };
  selectTreeTableRef.value?.acceptParams(params);
};
const supplierList = ref([]);
// const storeList = ref([]);
onMounted(async () => {
  try {
    const [supplier] = await Promise.all([
      getSupplierList()
      // getStoreList()
      // useSelectStore().getDic("DiscountType")
    ]);
    supplierList.value = supplier.data.list;
    // storeList.value = store.data.list;
    if (route.query.id) {
      isEdit.value = true;
      getStockin({ id: route.query.id }).then(res => {
        Object.keys(purchaseForm).forEach(key => {
          if (res.data.hasOwnProperty(key)) {
            purchaseForm[key] = res.data[key];
          }
        });
      });
    } else {
      // purchaseForm.storeId = store.data.list[0].id;
      purchaseForm.supplierId = supplier.data.list[0].id;
    }
  } catch (error) {
    // 错误处理逻辑
    console.error("An error occurred:", error);
  }
});
</script>

<style lang="scss" scoped>
.section-title {
  padding-left: 4px;
  margin-bottom: 26px;
  font-size: 14px;
  font-weight: 700;
  line-height: 14px;
  color: #333333;
  border-left: 4px solid var(--el-color-primary);
}
.select-day-in-week-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 638px;
  padding: 12px 14px;
  font-family: PingFangSC-Regular;
  color: #222222;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}
</style>
